{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "QUANTAXIS>> start QUANTAXIS\n",
      "QUANTAXIS>> Welcome to QUANTAXIS, the Version is 1.1.0\n",
      "QUANTAXIS>>  \n",
      " ```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` \n",
      "  ``########`````##````````##``````````##`````````####````````##```##########````````#``````##``````###```##`````######`` \n",
      "  `##``````## ```##````````##`````````####````````##`##```````##```````##```````````###``````##````##`````##```##`````##` \n",
      "  ##````````##```##````````##````````##`##````````##``##``````##```````##``````````####```````#```##``````##```##``````## \n",
      "  ##````````##```##````````##```````##```##```````##```##`````##```````##`````````##`##```````##`##```````##````##``````` \n",
      "  ##````````##```##````````##``````##`````##``````##````##````##```````##````````##``###```````###````````##`````##`````` \n",
      "  ##````````##```##````````##``````##``````##`````##`````##```##```````##```````##````##```````###````````##``````###```` \n",
      "  ##````````##```##````````##`````##````````##````##``````##``##```````##``````##``````##`````##`##```````##````````##``` \n",
      "  ##````````##```##````````##````#############````##```````##`##```````##`````###########`````##``##``````##`````````##`` \n",
      "  ###```````##```##````````##```##```````````##```##```````##`##```````##````##`````````##```##```##``````##```##`````##` \n",
      "  `##``````###````##``````###``##`````````````##``##````````####```````##```##``````````##``###````##`````##````##`````## \n",
      "  ``#########``````########```##``````````````###`##``````````##```````##``##````````````##`##``````##````##`````###``### \n",
      "  ````````#####`````````````````````````````````````````````````````````````````````````````````````````````````````##``  \n",
      "  ``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` \n",
      "  ``````````````````````````Copyright``yutiansut``2018``````QUANTITATIVE FINANCIAL FRAMEWORK````````````````````````````` \n",
      "  ``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` \n",
      " ```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` \n",
      " ```````````````````````````````````````````````````````````````````````````````````````````````````````````````````````` \n",
      " \n"
     ]
    }
   ],
   "source": [
    "from QUANTAXIS.QAARP.QAStrategy import QA_Strategy\n",
    "from QUANTAXIS.QAARP.QAAccount import  QA_Account\n",
    "from QUANTAXIS.QAUtil.QAParameter import (AMOUNT_MODEL, MARKET_TYPE,\n",
    "                                          FREQUENCE, ORDER_DIRECTION,\n",
    "                                          ORDER_MODEL,RUNNING_ENVIRONMENT)\n",
    "import QUANTAXIS as QA\n",
    "\n",
    "import random\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MAMINT0Strategy(QA_Account):\n",
    "    def __init__(self,init_hold={'000001':10000,'000002':20000,'000004':40000}):\n",
    "        super().__init__(init_hold=init_hold)\n",
    "        self.running_environment=RUNNING_ENVIRONMENT.TZERO\n",
    "        self.frequence = FREQUENCE.FIFTEEN_MIN\n",
    "        self.market_type = MARKET_TYPE.STOCK_CN\n",
    "        self.account_cookie ='LCW_T0'\n",
    "\n",
    "    def on_bar(self, event):\n",
    "        try:\n",
    "            for item in event.market_data.code:\n",
    "\n",
    "                print(self.current_time)\n",
    "                print(self.datetime)\n",
    "                print('=====SELL_AVAILABLE======')\n",
    "                print(self.sell_available)\n",
    "                print('=====HOLD_AVAILABLE======')\n",
    "                print(self.hold_available)\n",
    "                print('=====BUY_AVAILABLE=======')\n",
    "                print(self.buy_available)\n",
    "                if self.sell_available.get(item, 0) > 0:\n",
    "                    event.send_order(account_cookie=self.account_cookie,\n",
    "                                        amount=int(self.sell_available[item]*random.random()/100)*100, amount_model=AMOUNT_MODEL.BY_AMOUNT,\n",
    "                                        time=self.current_time, code=item, price=0,\n",
    "                                        order_model=ORDER_MODEL.MARKET, towards=ORDER_DIRECTION.SELL,\n",
    "                                        market_type=self.market_type, frequence=self.frequence,\n",
    "                                        broker_name=self.broker\n",
    "                                        )\n",
    "                if random.random()>0.5:\n",
    "                    event.send_order(account_cookie=self.account_cookie,\n",
    "                                        amount=random.randint(1,50)*100, amount_model=AMOUNT_MODEL.BY_AMOUNT,\n",
    "                                        time=self.current_time, code=item, price=0,\n",
    "                                        order_model=ORDER_MODEL.MARKET, towards=ORDER_DIRECTION.BUY,\n",
    "                                        market_type=self.market_type, frequence=self.frequence,\n",
    "                                        broker_name=self.broker)\n",
    "        except:\n",
    "            pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MAMINT0Strategy1(QA_Account):\n",
    "    def __init__(self,init_hold={'000001':10000,'000004':20000,'000008':40000}):\n",
    "        super().__init__(init_hold=init_hold)\n",
    "        self.running_environment=RUNNING_ENVIRONMENT.TZERO\n",
    "        self.frequence = FREQUENCE.FIFTEEN_MIN\n",
    "        self.market_type = MARKET_TYPE.STOCK_CN\n",
    "        self.account_cookie ='LCW_T01'\n",
    "\n",
    "    def on_bar(self, event):\n",
    "        try:\n",
    "            for item in event.market_data.code:\n",
    "\n",
    "                print(self.current_time)\n",
    "                print(self.datetime)\n",
    "                print('=====SELL_AVAILABLE======')\n",
    "                print(self.sell_available)\n",
    "                print('=====HOLD_AVAILABLE======')\n",
    "                print(self.hold_available)\n",
    "                print('=====BUY_AVAILABLE=======')\n",
    "                print(self.buy_available)\n",
    "                if self.sell_available.get(item, 0) > 0:\n",
    "                    event.send_order(account_cookie=self.account_cookie,\n",
    "                                        amount=int(self.sell_available[item]*random.random()/100)*100, amount_model=AMOUNT_MODEL.BY_AMOUNT,\n",
    "                                        time=self.current_time, code=item, price=0,\n",
    "                                        order_model=ORDER_MODEL.MARKET, towards=ORDER_DIRECTION.SELL,\n",
    "                                        market_type=self.market_type, frequence=self.frequence,\n",
    "                                        broker_name=self.broker\n",
    "                                        )\n",
    "                if random.random()>0.5:\n",
    "                    event.send_order(account_cookie=self.account_cookie,\n",
    "                                        amount=random.randint(1,50)*100, amount_model=AMOUNT_MODEL.BY_AMOUNT,\n",
    "                                        time=self.current_time, code=item, price=0,\n",
    "                                        order_model=ORDER_MODEL.MARKET, towards=ORDER_DIRECTION.BUY,\n",
    "                                        market_type=self.market_type, frequence=self.frequence,\n",
    "                                        broker_name=self.broker)\n",
    "        except:\n",
    "            pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "account1=MAMINT0Strategy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "account2=MAMINT0Strategy1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "user=QA.QA_User(user_cookie='LCW')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "< QA_Account LCW_T01>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "account2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "port=user.new_portfolio(portfolio_cookie='LCW_t0')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "port.add_account(account1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "port.add_account(account2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>amount</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>code</th>\n",
       "      <th>account_cookie</th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>000001</th>\n",
       "      <th>LCW_T0</th>\n",
       "      <td>10000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>000002</th>\n",
       "      <th>LCW_T0</th>\n",
       "      <td>20000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>000004</th>\n",
       "      <th>LCW_T0</th>\n",
       "      <td>40000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>000001</th>\n",
       "      <th>LCW_T01</th>\n",
       "      <td>10000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>000004</th>\n",
       "      <th>LCW_T01</th>\n",
       "      <td>20000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>000008</th>\n",
       "      <th>LCW_T01</th>\n",
       "      <td>40000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                       amount\n",
       "code   account_cookie        \n",
       "000001 LCW_T0           10000\n",
       "000002 LCW_T0           20000\n",
       "000004 LCW_T0           40000\n",
       "000001 LCW_T01          10000\n",
       "000004 LCW_T01          20000\n",
       "000008 LCW_T01          40000"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "port.init_hold_table"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "#pd.concat([account.init_hold_with_account for account in list(port.accounts.values())]).groupby('code').sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "from QUANTAXIS.QAARP.QARisk import QA_Risk\n",
    "from QUANTAXIS.QAARP.QAUser import QA_User\n",
    "from QUANTAXIS.QAApplication.QABacktest import QA_Backtest\n",
    "from QUANTAXIS.QAUtil.QALogs import QA_util_log_info\n",
    "from QUANTAXIS.QAUtil.QAParameter import FREQUENCE, MARKET_TYPE\n",
    "\n",
    "\n",
    "class Backtest(QA_Backtest):\n",
    "    '''\n",
    "    多线程模式回测示例\n",
    "\n",
    "    '''\n",
    "\n",
    "    def __init__(self, market_type, frequence, start, end, code_list, commission_fee):\n",
    "        super().__init__(market_type,  frequence, start, end, code_list, commission_fee)\n",
    "        self.user = QA_User()\n",
    "        t0strategy=MAMINT0Strategy()\n",
    "        # maminstrategy.reset_assets(1000)\n",
    "        # self.portfolio, self.account = self.user.register_account(mastrategy)\n",
    "        self.user = QA_User(user_cookie='user_admin')\n",
    "        self.portfolio = self.user.new_portfolio('folio_admin')\n",
    "        self.portfolio, self.account = self.user.register_account(t0strategy)\n",
    "\n",
    "    def after_success(self):\n",
    "        QA_util_log_info(self.account.history_table)\n",
    "        risk = QA_Risk(self.account, benchmark_code='000300',\n",
    "                       benchmark_type=MARKET_TYPE.INDEX_CN)\n",
    "\n",
    "        print(risk().T)\n",
    "\n",
    "        self.account.save()\n",
    "        risk.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "backtest = Backtest(market_type=MARKET_TYPE.STOCK_CN,\n",
    "                    frequence=FREQUENCE.FIFTEEN_MIN,\n",
    "                    start='2018-08-01',\n",
    "                    end='2018-08-05',\n",
    "                    code_list=['000001','000002','000004'],\n",
    "                    commission_fee=0.00015)\n",
    "backtest.start_market()\n",
    "\n",
    "backtest.run()\n",
    "backtest.stop()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "backtest.account.hold_available"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "backtest.account.orders.queue_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "risk=QA.QA_Risk(backtest.account)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "risk.profit_construct"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "backtest.account.init_assets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "backtest.account.daily_hold"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "risk.plot_assets_curve()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
